﻿using System;
using System.IO;

namespace utils
{
    public class writeExceptionLogUtil
    {

            public static void writeLogException(Exception ex, string sFilePath, string programName) //异常信息写入日志
            {
                //获取异常信息的类、行号、异常 信息
                string exceptionStr =
                    ex.StackTrace.ToString().Substring(ex.StackTrace.ToString().LastIndexOf('\\') + 1)
                    + "  " + ex.Message;
                exceptionStr = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "  " + exceptionStr;
                //自己定义一个存储日志文件的位置
                string sFileName = programName +"-"+ DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                sFileName = sFilePath + @"/" + sFileName; //文件
                if (!Directory.Exists(sFilePath)) 
                {
                    Directory.CreateDirectory(sFilePath);
                }
                FileStream fs;
                StreamWriter sw;
      
                if (System.IO.File.Exists(sFileName))
                {
                    fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                }
                else
                {
                    fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                }
                sw = new StreamWriter(fs);
                sw.WriteLine(exceptionStr);
                sw.Close();
                fs.Close();
            }

        }
   
}